﻿package com.projects.xenia.documents_activities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import com.projects.xenia.Activity_CustomersInfo;
import com.projects.xenia.Documents_Location;
import com.projects.xenia.MainCustomersListActivity;
import com.projects.xenia.R;
import com.projects.xenia.Documents_Location.GPSStateEnum;
import com.projects.xenia.R.id;
import com.projects.xenia.documents_classes.Documents_PhotoReport;
import com.projects.xenia.global_modules.MainGlobalModule;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Bitmap.CompressFormat;


import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;


public class Activity_PhotoReport extends Activity { 

	private final Context Ctx = this;
	
	private final int IDR_CustomerSelect = 0;
	private final int IDR_GetPhoto = 1;
	private final int IDR_GPSSettingsTest = 3;
	private final int IDR_MobileNetworkSettingsTest = 4;
	
	private Documents_PhotoReport DocumentClass;
	
	private SimpleCursorAdapter adap;	
	
	private Cursor PhotoReportItemsCursor;
	private EfficientAdapter PhotoReportItemsAdapter;
	
	private Cursor PhotoReportTypesCursor;
	private SimpleCursorAdapter PhotoReportTypesAdapter;
	
	private Button PhotoReportDate;	
	private Button PhotoReportCustomer;
	
	private ListView DocPhotoReportList;
		
	private int SelectedPhotoReportListItemIndex;
	
	private ImageView PhotoReportGpsState;
	
	private String photoreportype_id;	  
	private String c_id;
	private String c_photoreportype_id;
	private String c_photoreportype_descr;	
	
	
	private ImageView add_photo;
	private ImageView _BackWard;
	
	private String NewFileId;
	private String sel_photoreportype_id;
	
	private File newFile; 
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		return (DocumentClass);		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		MainGlobalModule.Documents_Location.StopLocation();
		MainGlobalModule.Documents_Location = null;
	}

	@Override
	protected void onPause() {
		super.onPause();
		
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {	
		super.onSaveInstanceState(outState);		
		outState.putString("sel_photoreportype_id", sel_photoreportype_id);		
		outState.putString("NewFileId", NewFileId);		
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {	
		super.onRestoreInstanceState(savedInstanceState);
		
		sel_photoreportype_id = savedInstanceState.getString("sel_photoreportype_id");	
		NewFileId = savedInstanceState.getString("NewFileId");	
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {	
		super.onCreate(savedInstanceState);
		
		if (MainGlobalModule.SettingsCollection.get("ManagerId").equals("")) {
			Toast xtoast = Toast.makeText(this, "Устройство не авторизовано !!!", Toast.LENGTH_SHORT);
			xtoast.show();
			finish();
		}
		
		if (!MainGlobalModule.CheckLocationToday(true)) {
			finish ();
		}
		
		if (!MainGlobalModule.CheckGPSSettings(false)) {			
			startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		}
		
		if (!MainGlobalModule.CheckMobileNetworkSettings()) {			
			startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS),IDR_MobileNetworkSettingsTest);
		}
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);            
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		setContentView(R.layout.photoreport_form);
		
		Bundle DocExtras;
		DocExtras = getIntent().getExtras();
		
		_BackWard = (ImageView)findViewById(R.id._backward);
    	_BackWard.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {				
				CloseDocument ();	
			}
		});
    	
		DocumentClass = (Documents_PhotoReport) getLastNonConfigurationInstance();
		
		if (DocumentClass== null) {			
			DocumentClass = new Documents_PhotoReport ();			
			if (DocExtras!=null) {
				if (DocExtras.getString("DocId")!=null) {
					DocumentClass.OpenDoc(DocExtras.getString("DocId"));
					}
				else {
					DocumentClass.NewDoc();
					DocumentClass.Head.customers_id = DocExtras.getString("CustomerId");
					}
			}	
			else {
				DocumentClass.NewDoc();
			}			
		}
		
		PhotoReportGpsState = (ImageView) findViewById(R.id.PhotoReportGpsState);
		PhotoReportGpsState.setVisibility(View.INVISIBLE);
		
		if (MainGlobalModule.Documents_Location==null) {
			MainGlobalModule.Documents_Location = new Documents_Location();
			MainGlobalModule.Documents_Location.StartLocation(this, MainGlobalModule.DocumentsType.PhotoReport, DocumentClass.Head.id,PhotoReportGpsState);
		}
		
		
		PhotoReportDate = (Button) findViewById(R.id.PhotoReportDate);
		RefreshDate (PhotoReportDate,DocumentClass.Head.date_create);
		
		PhotoReportCustomer = (Button) findViewById(R.id.PhotoReportCustomer);
		PhotoReportCustomer.setOnClickListener(PhotoReportCustomerSelect);
		PhotoReportCustomer.setOnLongClickListener(CustomerLongSelect);
		RefreshByCursor (PhotoReportCustomer , "xref_customers", DocumentClass.Head.customers_id);		
				
		GetPhotoReportItemsCursorByDocId();
		
		DocPhotoReportList = (ListView)findViewById(id.DocPhotoReportList);
		PhotoReportItemsAdapter = new EfficientAdapter(this);
		DocPhotoReportList.setAdapter(PhotoReportItemsAdapter);
		
		DocPhotoReportList.setOnItemLongClickListener(DocPhotoReportList_OnItemLongClickListener);		
		
		add_photo = (ImageView)findViewById(R.id.add_photo);
		add_photo.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				_addphoto ();		
			}
		});
		
	}
	
	private DialogInterface.OnClickListener DocPhotoReportList_DialogListener = new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
	    	
	    	PhotoReportItemsCursor.moveToPosition(SelectedPhotoReportListItemIndex);
	    	
	    	switch (which) {
				
			case 1:
			
				String _id = PhotoReportItemsCursor.getString(0); 
				DocumentClass.DeleteDocLineById (_id);
				 
				File MyFile = new File(String.format ("%s/%s.jpg",MainGlobalModule.PhotoReportsImagesPath,_id));
				if (MyFile.exists()) {
					MyFile.delete();
				};				
				
				PhotoReportItemsCursor.requery();
				PhotoReportItemsAdapter.notifyDataSetChanged();
				DocPhotoReportList.setAdapter(PhotoReportItemsAdapter);
				
				break;
				
			}
	    }
	};
	
	private OnItemLongClickListener DocPhotoReportList_OnItemLongClickListener = new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int position, long arg3) {
			
			SelectedPhotoReportListItemIndex = position; 
			AlertDialog.Builder adb = new AlertDialog.Builder(Ctx);			
			adb.setItems(new String [] {"Просмотр","Удалить"} ,DocPhotoReportList_DialogListener);
			Dialog alert = adb.create();
			alert.show(); 
					
			return true;
			
		}
		
	};
	 
	private void RefreshDate (Button DateButton,Date DateValue) {
		
		SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
		DateButton.setText(sdf.format(DateValue));
		
	}	
	
	private void RefreshByCursor (Button SelectButton, String Table, String Id) {
		
		try {
			Cursor ScalarCursor = MainGlobalModule.DBE.query (Table, new String []{"descr"}, "id = ?", new String []{Id}, null, null, null);
			ScalarCursor.moveToFirst();
			SelectButton.setText(ScalarCursor.getString(0));
		} catch (Exception e) {
			SelectButton.setText ("");
		}
		
	}
	
	private OnClickListener PhotoReportCustomerSelect= new OnClickListener () {	
		
		@Override
		public void onClick(View v) {			
			Intent CustomerSelectintent = new Intent();
			CustomerSelectintent.setClass(Ctx,MainCustomersListActivity.class);
			CustomerSelectintent.putExtra("customer_id", DocumentClass.Head.customers_id);
			CustomerSelectintent.putExtra("customer_descr","");
            startActivityForResult (CustomerSelectintent,IDR_CustomerSelect);			
		}
		
	};
	
	private OnLongClickListener CustomerLongSelect = new OnLongClickListener() {		
		@Override
		public boolean onLongClick(View v) {
			
			if (DocumentClass.Head.customers_id != null) {
				Intent CustomerInfoIntent = new Intent();
				CustomerInfoIntent.putExtra("CustomerId", DocumentClass.Head.customers_id);
				CustomerInfoIntent.setClass(Ctx,Activity_CustomersInfo.class);
		    	startActivity(CustomerInfoIntent);	
			}
			return true;
		}
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {	
		 
		 switch(requestCode) { 
		    case IDR_CustomerSelect:
		    	if (resultCode==RESULT_OK) {
		    		PhotoReportCustomer.setText(data.getStringExtra("customer_descr"));
		    		DocumentClass.Head.state = 1;
		    		DocumentClass.Head.customers_id = data.getStringExtra("customer_id");
		    	}
		    	break;  	
		    case IDR_GPSSettingsTest:		    	
		    	if (!MainGlobalModule.CheckGPSSettings(false)) {			
		    		startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),IDR_GPSSettingsTest);
		    	}		    	
		    	break;
		    case IDR_MobileNetworkSettingsTest:
		    	if (!MainGlobalModule.CheckMobileNetworkSettings()) {
		    		startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS),IDR_MobileNetworkSettingsTest);
		    	}
		    	break;
		    case IDR_GetPhoto:
		    	if (resultCode==RESULT_OK) {

		    		try {
						
		    			newFile = new File(String.format ("%s/%s.jpg",MainGlobalModule.PhotoReportsImagesPath,NewFileId)); 
		    			
		    			FileInputStream ifs1 = new FileInputStream(newFile);		    		
		    			BitmapFactory.Options BitmOptions1 = new BitmapFactory.Options();		    		
		    			BitmOptions1.inJustDecodeBounds = true;
		    			BitmapFactory.decodeStream(ifs1, null, BitmOptions1);
		    			ifs1.close();
		    		
		    			int origWidth = BitmOptions1.outWidth; 
		    			int origHeight = BitmOptions1.outHeight;
		    		
		    			int desiredWidth = 1024; 
		    			int desiredHeight = 1024;
		    			
		    			int scale = 1;		    					
		    			
		    			if (origWidth > origHeight) {
		    				scale = Math.round((float) origHeight / (float) desiredHeight);		    							    					
		    			}
		    			else {
		    				scale = Math.round((float) origWidth / (float) desiredWidth);
		    			}
		    		
		    			BitmapFactory.Options BitmOptions2 = new BitmapFactory.Options();
		    			BitmOptions2.inJustDecodeBounds = false;
		    			BitmOptions2.inSampleSize = scale;
		    			BitmOptions2.inPreferredConfig = Config.RGB_565;		    			
		    			
		    			FileInputStream ifs2 = new FileInputStream(newFile);		    		
		    			Bitmap ResizedImage = BitmapFactory.decodeStream(ifs2, null, BitmOptions2);		    			
		    			ifs1.close();
		    		
		    			
		    			FileOutputStream ofs = new FileOutputStream (newFile);                            
		    			ResizedImage.compress(CompressFormat.JPEG,75, ofs);
		    			ofs.close();                                        
                	
		    			DocumentClass.Line.docline = 1;
		    			DocumentClass.Line.id = NewFileId;
		    			DocumentClass.Line.hdoc_id = DocumentClass.Head.id;
		    			DocumentClass.Line.photoreportype_id = sel_photoreportype_id;
		    			DocumentClass.UpdateInsertDocLine();
		    			PhotoReportItemsCursor.requery();			    	
		    			DocPhotoReportList.setAdapter(PhotoReportItemsAdapter);
			    	
					} catch (Exception e) {
						
						Toast.makeText(this, "Ошибка записи изображения", Toast.LENGTH_SHORT).show();
						Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
						
					}
		    		
		    	}
		    	
		    	break;
		 }		 
		    	
	};	
	
    public boolean onCreateOptionsMenu (Menu menu){
    	
    	menu.add(Menu.NONE,1,Menu.NONE,"Добавить/Изменить");
    	menu.add(Menu.NONE,2,Menu.NONE,"Записать");
    	menu.add(Menu.NONE,3,Menu.NONE,"Выход");
    	
		return true;    	
    }
	
    private void GetPhotoReportTypesCursorByDocId () {
    	
    	try {
    		PhotoReportTypesCursor = MainGlobalModule.DBE.rawQuery("select distinct a.id as _id, a.descr as descr from xref_PhotoReportTypes a order by a.descr ", null);	
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    }
      
    private void GetPhotoReportItemsCursorByDocId () {
    	
    	try {
    		PhotoReportItemsCursor = MainGlobalModule.DBE.rawQuery("select a.id,a.photoreportype_id,b.descr from xdoc_photoreports_t a left outer join xref_PhotoReportTypes b on a.photoreportype_id = b.id where a.hdoc_id = ?", new String [] {DocumentClass.Head.id});	
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    }    
 
    
    private DialogInterface.OnClickListener PhotoReportTypesSelectDialogListener = new DialogInterface.OnClickListener() {	
    	@Override
    	public void onClick(DialogInterface dialog, int which) {
    		
    		PhotoReportTypesCursor.moveToPosition(which);    		
    		sel_photoreportype_id = PhotoReportTypesCursor.getString(0);
    		
    		NewFileId = UUID.randomUUID().toString().toUpperCase(); 
    		newFile = new File(String.format ("%s/%s.jpg",MainGlobalModule.PhotoReportsImagesPath,NewFileId));    		
    		newFile.setLastModified(Calendar.getInstance().getTimeInMillis());
    		
    		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile));            
            
            startActivityForResult(intent, IDR_GetPhoto);
    		
    		//Intent cameraIntent = new Intent();
    		//cameraIntent.setClass(Ctx, DVCameraActivity.class);
    		//startActivityForResult(cameraIntent,IDR_GetPhoto);
    		
    	}
    };

    
    private void _addphoto () {
    	
    	GetPhotoReportTypesCursorByDocId ();
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	
    	try {
			PhotoReportTypesAdapter	= new SimpleCursorAdapter(this, R.layout.listview_item_checked,PhotoReportTypesCursor , new String[] {"descr"}, new int[] {R.id.checkedTextView1});    				
		} catch (Exception e) {
			e.printStackTrace();
		}    			
	

		builder.setTitle("Укажите категорию фото");
		builder.setAdapter(PhotoReportTypesAdapter, PhotoReportTypesSelectDialogListener);
		AlertDialog typPicker = builder.create();
		typPicker.show();
		
    }
    
    
    private void CloseDocument () {
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	GPSStateEnum state = MainGlobalModule.Documents_Location.GetGPSState(DocumentClass.Head.id); 
		
		if (state != GPSStateEnum.accurate){    				
			
			String AddString = (state==GPSStateEnum.none?"Координата":"Точная координата");
			builder.setTitle(AddString.concat (" не определена !!! "));
			builder.setMessage("Хотите продолжить без определения ?");
			builder.setPositiveButton("Да,закрыть документ", new DialogInterface.OnClickListener() {    				    
				public void onClick(DialogInterface dialog, int which) {
					FinishActivity ();
			        dialog.dismiss();
			    }
			});

			builder.setNegativeButton("Нет,подождать", new DialogInterface.OnClickListener() {
			    @Override
			    public void onClick(DialogInterface dialog, int which) {
			        dialog.dismiss();
			    }
			});

			Dialog alert = builder.create();
			alert.show();    				
		}
		else
		{
			FinishActivity();
		}
    }
    
    public void FinishActivity () {
	 		
	 		DocumentClass.Head.state = 1;
	    	DocumentClass.Head.verstamp++;
	    	DocumentClass.UpdateDoc();
	    	DocumentClass.FinishDoc ();
	    	finish();    	
	 			
	 	}	
	

  public boolean onOptionsItemSelected (MenuItem item){    	
    	
    	
    	
    	switch (item.getItemId()) {
    	
    		case 1:    			
    			
    					
    		
    			_addphoto (); 
    			
    			break;
    			
    		case 3:
    			
    			CloseDocument ();
    			
    			return true;
    			
    		case 2:  
    			DocumentClass.Head.state = 1;
    			DocumentClass.UpdateDoc();
    			return (true);
    			
    		}    		
    			return false;
    			
    }
   
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {		
		
		switch (keyCode){
		
    		case KeyEvent.KEYCODE_BACK:    			
    			return false;   			
    		
    	}	
		return super.onKeyDown(keyCode, event);
	}
	
 	
 	
 	
public class EfficientAdapter extends BaseAdapter  {
		
		private LayoutInflater mInflater;
		public Context context;
				
		
		public EfficientAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;
		}
		 
		public View getView(final int position, View convertView, ViewGroup parent) {	
			
			ViewHolder holder;
		
			if (convertView == null) {			
				convertView = mInflater.inflate(R.layout.photoreport_list, null);
			}
			
			holder = new ViewHolder();
		
			holder.textLine = (TextView) convertView.findViewById(R.id.phr_txt);
			holder.imageLine = (ImageView) convertView.findViewById(R.id.ibutton);	
					
			getItem(position);
		
			holder.textLine.setText(c_photoreportype_descr);
			holder.textLine.setTextColor(Color.WHITE);
			
			File ImgPath = new File (MainGlobalModule.PhotoReportsImagesPath+"/"+c_id+".jpg");
			if (ImgPath.exists()) {				
				BitmapFactory.Options BitmOptions = new BitmapFactory.Options();
    			BitmOptions.inJustDecodeBounds = false;
    			BitmOptions.inSampleSize = 5;
    			BitmOptions.inPreferredConfig = Config.RGB_565;
				holder.imageLine.setImageBitmap(BitmapFactory.decodeFile(ImgPath.getAbsolutePath(),BitmOptions));
			}			
				
			return convertView;
		
		}
		 
		class ViewHolder {
			
			TextView textLine;		
			ImageView imageLine;
			
		}
		 
				 
		@Override
		public long getItemId(int position) {
			return 0;
		}
		 
		@Override
		public int getCount() {
			return PhotoReportItemsCursor.getCount();
		}
		 
		@Override
		public Object getItem(int position) {
			
		PhotoReportItemsCursor.moveToPosition(position);
		
		c_id = PhotoReportItemsCursor.getString(0);
		c_photoreportype_id = PhotoReportItemsCursor.getString(1);
		c_photoreportype_descr = PhotoReportItemsCursor.getString(2);
		
		return 0;
		
		}
	
	}

 	
 
}
